<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/11 11:06
 * Desc:
 */
class Service_Api_Line extends Contract_Api_Product
{

    /**
     * 线路类型ID
     */
    const TYPE_ID = 1;

    public function search(array $params = array()): array
    {
        /**
         * @var $dest_pinyin
         * @var $day_id
         * @var $price_id
         * @var $sort_type
         * @var $start_city_id
         * @var $attr_id
         * @var $page
         * @var $pagesize
         * @var $keyword
         * @var $mid
         */
        extract($params);

        $dest_pinyin   = $dest_pinyin ?? '';
        $price_id      = $price_id ?? '';
        $sort_type     = $sort_type ?? '';
        $start_city_id = $start_city_id ?? '';
        $attr_id       = $attr_id ?? '';
        $page          = $page ?? '';
        $pagesize      = $pagesize ?? '';

        $builder = DB::select(DB::expr('`sline_line`.*,(IFNULL(`sline_line`.bookcount,0)+IFNULL(`sline_member_order_statistic`.sell_num,0)) AS sell_num'))
            ->from('line');

        //排序
        $order_by = "";
        if (!empty($sort_type)) {
            switch ($sort_type) {
                case 1:
                    $order_by = "`sline_line`.price ASC,";
                    break;
                case 2:
                    $order_by = "`sline_line`.price DESC,";
                    break;
                case 3:
                    $order_by = "sell_num desc,";
                    break;
                case 4:
                    $order_by = "`sline_line`.recommendnum DESC,";
                    break;
                default:
                    break;
            }
        }

        //按目的地搜索
        if ($dest_pinyin && $dest_pinyin != 'all') {
            $dest_id = Model_Destinations::get_id_by_pinyin($dest_pinyin);
        }
        if (!empty($dest_id)) {
            $builder->join('kindorderlist', 'left')
                ->on('line.id', '=', DB::expr('`sline_kindorderlist`.aid'))
                ->on('line.webid', '=', DB::expr('`sline_kindorderlist`.webid'))
                ->on('kindorderlist.typeid', '=', self::TYPE_ID)
                ->on('kindorderlist.classid', '=', DB::expr("{$dest_id}"));
            $order_by .= "IFNULL(`sline_kindorderlist`.displayorder,9999) ASC,";
        } else {
            $builder->join('allorderlist', 'left')
                ->on('line.id', '=', DB::expr('`sline_allorderlist`.aid'))
                ->on('line.webid', '=', DB::expr('`sline_allorderlist`.webid'))
                ->on('allorderlist.typeid', '=', self::TYPE_ID);
            $order_by .= "IFNULL(`sline_allorderlist`.displayorder,9999) ASC,";
        }

        // 需要提前处理真实购买量
        $builder->join('member_order_statistic', 'left')
            ->on('member_order_statistic.product_id', '=', DB::expr('`sline_line`.id'))
            ->on('member_order_statistic.type_id', '=', self::TYPE_ID);

        $builder->where('line.ishidden', '=', 0)
            ->and_where('line.status', '=', 3);
        if (!empty($dest_id)) {
            $builder->and_where(DB::expr(" AND FIND_IN_SET('$dest_id',sline_line.kindlist) "));
        }

        //天数
        if ($day_id) {
            $day = DB::select('word')
                ->from('line_day')
                ->where('id', '=', $day_id)
                ->execute()
                ->get('word', 0);
            if (!empty($day)) {
                if ($this->is_last_day($day)) {
                    $builder->and_where('line.lineday', '>=', $day);
                } else {
                    $builder->and_where('line.lineday', '=', $day);
                }
            }
        }
        //价格区间
        if ($price_id) {
            $price_arr = DB::select()
                ->from('line_pricelist')
                ->where('id', '=', $price_id)
                ->execute()
                ->current();
            if (!empty($price_arr)) {
                $builder->and_where(DB::expr(" AND sline_line.price BETWEEN {$price_arr['lowerprice']} AND {$price_arr['highprice']}"));
            }
        }
        //出发城市
        if (!empty($start_city_id)) {
            $city = Model_Startplace::start_city($start_city_id);
            if (!empty($city)) {
                $builder->and_where('line.startcity', '=', $start_city_id);
            }
        }
        //按属性
        if (!empty($attr_id)) {
            $attr_where = $this->get_attr_where($attr_id);
            if ($attr_where) {
                $builder->and_where(DB::expr($attr_where));
            }
        }
        //按关键词
        if (!empty($keyword)) {
            if (preg_match('`([a-zA-Z])(\d{3,8})`', $keyword, $preg)) {
                $id = ltrim($preg[2], '0');
                $builder->and_where('line.id', '=', $id);
            } else if (is_numeric($keyword)) {
                $product_id = St_Product::product_series_decode($keyword, self::TYPE_ID);
                if($product_id) {
                    $builder->and_where_open();
                }
                $builder->and_where('line.title', 'like', '%' . $keyword . '%');
                if ($product_id) {
                    $builder->or_where('line.id', '=', $product_id);
                    $builder->and_where_close();
                }
            } else {
                $builder->and_where('line.title', 'like', '%' . $keyword . '%');
            }
        }
        $total = $builder->execute()->count();
        //检测页面数量是否超限
        $status     = true;
        $total_page = (int)ceil($total / $pagesize);
        if (($total_page > 0 and intval($page) > $total_page) or ($total_page == 0 and $page > 1)) {
            $status = false;
        }

        if ($page && $pagesize) {
            $offset = St_Page::offset($page, $pagesize);
            $builder->offset($offset)->limit($pagesize);
        }

        $builder->order_by(DB::expr("{$order_by}sline_line.modtime DESC,sline_line.addtime DESC"));
        $list = $builder->execute()->as_array();

        $filter_keys = array('id', 'title', 'start_city', 'litpic', 'show_num', 'price', 'attr_list', 'score', 'sell_num', 'icon_list');

        $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID);

         if(!empty($list)){
            // 获取营销策略
            $marketing_strategy = Model_Api_V2_Marketing_Strategy::get_instance(self::TYPE_ID, array('mid'=> $mid));

            foreach ($list as &$v) {
                $v['show_num']           = intval($v['shownum']);
                $v['price']              = Model_Line::get_minprice($v['id'], array('info' => $v));
                $v['attr_list']          = Model_Line::line_attr($v['attrid']);
                $v['attr_list']          = $v['attr_list'] ?: array();
                $v['start_city']         = Model_Startplace::start_city($v['startcity']);
                $v['score']              = St_Functions::get_satisfy(self::TYPE_ID, $v['id'], $v['satisfyscore']);
                if (isset($uni_img[$v['id']])) {
                    $v['litpic'] = $this->img_url($uni_img[$v['id']], 220, 220);
                } else {
                    $v['litpic'] = $this->img_url($v['litpic'], 220, 220);
                }
                $v['icon_list']          = $this->icons($v['iconlist']);
                $v                       = $this->filter_data($filter_keys, $v);
                $v['group_period']       = self::group_period($v['id']);
                $v['marketing_strategy'] = $marketing_strategy->get_support_application($v['id']);
            }
        }

        return array(
            'total' => $total,
            'list' => $list,
            'status' => $status
        );
    }

    /**
     * @param $line_id
     * @return string|null
     * 线路团期获取
     */
    public function group_period($line_id)
    {
        $date = strtotime(date('Y-m-d'));
        $price = DB::select()->from('line_suit_price')
            ->where('lineid','=',$line_id)
            ->and_where('day','>=',$date)
            ->order_by('day','asc')
            ->group_by('day')
            ->offset(0)
            ->limit(4)
            ->execute()->as_array();
        $day = null;
        if(count($price)>0){
            $day = array_column($price,'day');
            foreach ($day as &$v) {
                $v = date('m-d',$v);
            }
            $day = implode('/',$day);
        }

        return $day;
    }

    public function info(array $params = array()): array
    {
        /**
         * @var $id
         * @var $userid
         */
        extract($params);

        $data = array();

        if (isset($id)) {
            $info = $this->get_detail($id);

            if (!empty($info)) {
                // 价格
                $info['price'] = Model_Line::get_minprice($info['id'], array('info' => $info));
                // 销售状态 0电询 1可订 2售罄
                $info['sell_out'] = St_Functions::is_sell_out(1,$info['id']);
                //会员折扣
                $cfg_line_minprice_rule     = $GLOBALS['cfg_line_minprice_rule'];
                $cfg_line_minprice_rule     = empty($cfg_line_minprice_rule) ? 2 : $cfg_line_minprice_rule;
                $info['discount_min_price'] = Model_Api_V2_Discount::get_discount($userid, self::TYPE_ID, $id, $info['price'], $cfg_line_minprice_rule);
                //出发城市
                $info['startcity'] = Model_Startplace::start_city($info['startcity']);
                //点评数
                $info['commentnum'] = Model_Comment::get_comment_num($info['id'], self::TYPE_ID);
                //销售数量
                $info['sellnum'] = Model_Member_Order_statistic::get_sell_num(self::TYPE_ID, $info['id']) + intval($info['bookcount']);
                //产品编号
                $info['series'] = St_Product::product_series($info['id'], self::TYPE_ID);
                //行程附件
                $info['linedoc']      = unserialize($info['linedoc']);
                $info['linedoc_path'] = empty($info['linedoc']['path']) ? '' : $this->reorganized_resource_url($info['linedoc']['path'][0]);
                //满意度
                $info['score'] = St_Functions::get_satisfy(self::TYPE_ID, $info['id'], $info['satisfyscore']);
                $uni_img = Model_Uniapp_Images::get_img_list(self::TYPE_ID,2);
                if(isset($uni_img['litpic'][$info['id']])){
                    $info['litpic'] = $this->img_url($uni_img['litpic'][$info['id']],750,750);
                }else{
                    //产品封面图片
                    $info['litpic'] = $this->img_url($info['litpic']);
                }
                if(isset($uni_img['piclist'][$info['id']])){
                    $info['piclist'] = $this->pic_list_url($uni_img['piclist'][$info['id']]);
                }else{
                    //产品图片
                    $info['piclist'] = $this->pic_list_url($info['piclist']);
                }
                //产品介绍
                $info['jieshao'] = $this->content_add_domain($info['jieshao']);
                //会员等级
                $info['rank_name'] = Model_Member::member_rank($userid, array('return' => 'current'));
                // 处理视频
                if ($info['product_video']) {
                    $product_video         = explode('|', $info['product_video']);
                    $info['product_video'] = isset($product_video[0]) ? $this->reorganized_resource_url($product_video[0]) : '';
                } else {
                    $info['product_video'] = '';
                }
                //套餐信息
                $info['suit_info'] = $this->suit($info['id']);
                //供应商信息
                if ($info['supplierlist']) {
                    $supplier_shop_service = new Service_Api_Supplier_Shop();
                    $info['suppliers'] = $supplier_shop_service->get_shop_info($info['supplierlist']);
                    if (!$info['suppliers']) {
                        $info['supplierlist'] = false;
                    }
                }
                //线路详情内容
                $info['detail_list'] = $this->get_detail_content($info);
                // 最近可预订日期
                $near_price_days = $this->get_near_price_days($info);
                foreach ($near_price_days as &$near_price_day) {
                    $near_price_day = $this->filter_data(array('day', 'min_price', 'rewardway', 'suitid'), $near_price_day);
                }
                $info['near_price_days'] = $near_price_days;
                // 积分抵现配置
                $jifenprice_info          = Model_Jifen_Price::get_used_jifentprice($info['jifentprice_id'], self::TYPE_ID);
                $info['jifentprice_info'] = $this->filter_data(array('isopen', 'id', 'toplimit', 'jifentprice'), $jifenprice_info);
                // 预定送积分
                $jifenbook_info         = Model_Jifen::get_used_jifenbook($info['jifenbook_id'], self::TYPE_ID);
                $info['jifenbook_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifenbook_info);
                //积分评论
                $jifencomment_info         = Model_Jifen::get_used_jifencomment(self::TYPE_ID);
                $info['jifencomment_info'] = $this->filter_data(array('isopen', 'value', 'rewardway'), $jifencomment_info);

                // 指定返回数据
                $filter_keys = array(
                    'id', 'piclist', 'product_video', 'title', 'sellpoint', 'detail_list', 'price', 'discount_min_price',
                    'status', 'ishidden', 'near_price_days', 'linedoc_path', 'score', 'supplierlist', 'suppliers',
                    'jifencomment_info', 'jifenbook_info', 'jifentprice_info', 'sellnum', 'storeprice', 'series',
                    'startcity', 'lineday', 'linenight', 'piclist', 'video_litpic', 'litpic',
                );
                $data        = $this->filter_data($filter_keys, $info);
            }
        }

        return $data;
    }

    public function query_condition(): array
    {
        $data = array(
            'sort' => array(
                array('id' => 0, 'name' => '综合排序'),
                array('id' => 1, 'name' => '价格从低到高'),
                array('id' => 2, 'name' => '价格从高到低'),
                array('id' => 3, 'name' => '销量最高'),
                array('id' => 4, 'name' => '产品推荐')
            ),
            'start_city' => array('name' => '出发地', 'child' => array()),
            'day' => array('name' => '天数', 'child' => array()),
            'price' => array('name' => '价格', 'child' => array()),
        );

        //出发地
        $data['start_city']['child'] = $this->start_city_filter();

        //属性
        $data['attribute'] = $this->attribute_filter();

        //天数
        $data['day']['child'] = $this->day_filter();

        //价格
        $data['price']['child'] = $this->price_filter();

        return $data;
    }

    /**
     * @param array $params
     * @return array
     * @throws Kohana_Exception
     * @throws Exception
     */
    public function create_order(array $params = array()): array
    {
        $mid         = $params['mid'];
        $member_info = $params['member_info'];

        // 参数检查
        list($info, $suit_info, $price_arr, $extend_data) = $this->check_order_params($params, $mid);

        // 初始化订单数据
        $order = $this->make_order_data($params, $info, $suit_info, $member_info);

        // 格式化报价信息
        $price_arr = $this->format_order_price($price_arr);

        $order['price']         = $price_arr['adultprice'];
        $order['childprice']    = $price_arr['childprice'];
        $order['oldprice']      = $price_arr['oldprice'];
        $order['people4_price'] = $price_arr['people4_price'];
        $order['people5_price'] = $price_arr['people5_price'];
        $order['people6_price'] = $price_arr['people6_price'];
        $order['roombalance']   = $price_arr['roombalance'];

        // 处理优惠券
        $coupon_id = Arr::get($params, 'coupon_id', 0);
        if ($coupon_id) {
            $coupon_check = Model_Api_V2_Coupon::order_use_coupon_check($coupon_id, $mid, $order);
        }

        // 订单附加信息
        $order_params = array(
            'member_card_id' => Arr::get($params, 'member_card_id', ''),
            'card_tourist_id' => Arr::get($params, 'card_tourist_id', ''),
        );

        // 判断拼团是否允许使用会员折扣
        if (isset($extend_data['together_info']['discount_limit'])) {
            if (!in_array(2, $extend_data['together_info']['discount_limit'])) {
                $order_params['use_member_discount'] = false;
            }
        }

        // 秒杀不使用会员折扣
        $seckill_id = Arr::get($params, 'seckill_id', '');
        if($seckill_id) {
            $order_params['use_member_discount'] = false;
        }

        // 添加订单
        $out = Model_Api_V2_Order::add_order($order, 'Model_Line', $order_params);
        if (!$out['status']) {
            throw new Exception($out['msg']);
        }

        // 订单添加成功
        $order_info            = Model_Member_Order::order_info($order['ordersn']);
        $order_id              = $order_info['id'];
        $order_info['orderid'] = $order_id;

        // 添加优惠券使用
        if(!empty($coupon_check)){
            Model_Coupon::add_coupon_order($coupon_check['cid'], $order['ordersn'], $coupon_check['order_total_price'], $coupon_check, $coupon_id);
        }

        // 添加拼团订单
        if (isset($extend_data['together_info'])) {
            Model_Api_V2_Together::add_order($extend_data['together_info'], $order_info);
        }

        // 添加秒杀订单
        $this->add_order_seckill($params, $price_arr, $order);

        // 游客信息
        $tourist = Arr::get($params, 'tourist', '');
        $tourist = $tourist ? json_decode($tourist, true) : '';

        // 添加游客信息
        $this->add_order_tourists($order_id, $tourist);

        // 添加订单保险信息
        $this->add_order_insurance($order, $tourist, $params);

        // 添加发票信息
        $this->add_order_bill_info($order_id, $params);

        // 添加红包抵扣
        $envelope_member_id = Arr::get($params, 'envelope_member_id', '');
        if ($envelope_member_id) {
            if (St_Functions::is_normal_app_install('red_envelope')) {
                Model_Order_Envelope::order_use_envelope($envelope_member_id, $order['ordersn'], self::TYPE_ID, $mid);
            }
        }

        // 订单结算信息表数据更新
        Model_Member_Order_Compute::update($order['ordersn']);

        // 预订事件
        Hook::trigger('order_created', $order_info);

        // 返回订单信息
        $filter_keys = array('id', 'orderid', 'ordersn', 'pageType', 'typeid', 'status');
        return $this->filter_data($filter_keys, $order_info);
    }

    use Trait_Api_Line;
}